package com.boco.pciv.controller.sys;

import cn.hutool.core.util.StrUtil;
import com.boco.pciv.SysProperties;
import com.boco.pciv.controller.PcivController;
import com.boco.pciv.core.annotion.BusiLog;
import com.boco.pciv.core.entity.*;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.core.util.UploadFileUtil;
import com.boco.pciv.entity.sys.UserInfo;
import com.boco.pciv.service.sys.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping(value="/sys/user/")
public class UserController extends PcivController {
	@Resource
	private IUserService svr;

	@Autowired
	SysProperties sysConfig;
	private  static Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/list")
	public PageResultBase getUserList(String userId,String roleId,String userType,LayUIPager pageParam){
		SearchCriteria param = new SearchCriteria();
		param.setPager(pageParam);
		param.putCriteria("userId", userId);
		param.putCriteria("roleId", roleId);
		LoginUser user=getCurUser();
		param.putCriteria("userType", user.getUserType());
		PageResultBase result= svr.getPage(param);
        addOperationLog("查询","用户信息查询");
		return result;
	}

	@GetMapping("/getUser")
	public BizResponse getUser() {
		LoginUser user = getCurUser();
		return BizResponseUtil.single(user);
	}

    @GetMapping("/info")
	public BizResponse getUserInfo(String id){
		UserInfo result= svr.getOneByUserId(id);
		return BizResponseUtil.single(result);
	}

    @PostMapping("/add")
	public BizResponse addUser(UserInfo user){
        if(user==null){
			return BizResponseUtil.fail("新增信息不能为空");
        }

		try{
			user.setPassword(sysConfig.getDefaultPassword());
			user.setCreateUser(getCurUserId());
			svr.add(user);
            addOperationLog("新增",String.format("新增用户:%s",user.getUserId()));
			return BizResponseUtil.success(MSG_ExeOK,sysConfig.getDefaultPassword());
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}

    @PostMapping("/delete")
    @BusiLog(action = "删除用户")
	public BizResponse deleteUser(String id){
		try{
			svr.deleteUserRoleByUserId(id);
			svr.deleteByUserId(id);
            addOperationLog("删除",String.format("删除用户:%s",id));
            return BizResponseUtil.success(MSG_ExeOK);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}

    @PostMapping("/unDelete")
    public BizResponse unDeleteUser(String id){
        try{
            svr.unDelete(id);
            addOperationLog("删除",String.format("取消删除用户：%s",id));
            return BizResponseUtil.success(MSG_ExeOK);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
    }

    @PostMapping("/lock")
	public BizResponse lockUser(String id){
		try{
			svr.lock(id);
            addOperationLog("锁定",String.format("锁定用户：%s",id));
            return BizResponseUtil.success(MSG_ExeOK);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}

    @PostMapping("/unLock")
	public BizResponse unLockUser(String id){
		try{
			svr.unLock(id);
            addOperationLog("锁定",String.format("解锁用户：%s",id));
            return BizResponseUtil.success(MSG_ExeOK);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}

    @PostMapping("/pwdResert")
	public BizResponse pwdResert(String id){
		try{
			String newpwd = sysConfig.getDefaultPassword();
			svr.modifyPassword(id,newpwd);
			addOperationLog("重置密码",String.format("重置密码：%s",id));
			return BizResponseUtil.success(MSG_ExeOK,newpwd);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}

    @PostMapping("/edit")
	public BizResponse editUser(UserInfo user){
        if(user==null){
            return BizResponseUtil.fail("用户信息不能为空");
        }



		user.setUpdateUser(getCurUserId());
        try{
			svr.edit(user);
            addOperationLog("编辑",String.format("编辑用户:%s",user.getUserId()));
            return BizResponseUtil.success(MSG_ExeOK);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}

    @PostMapping("/checkOldPassword")
	public String checkOldPassword(String oldPassword){
        String userId = getCurUserId();

        if(svr.testLogin(userId, oldPassword)){
            return "true";
        }
        else {
			return "false";
		}
    }

    @GetMapping("/checkUIdValidate")
	public String checkUIdValidate(String uid){
		UserInfo info = svr.getOneByUserId(uid);
		if(info!=null){
			return "false";
		}
		else {
			return "true";
		}
	}

    @PostMapping("/modifyPassword")
    public BizResponse modifyPassword(String oldPassword, String newPassword){
		String userId = getCurUserId();
        if(StrUtil.isBlank(oldPassword)){
            return BizResponseUtil.fail("原密码不正确");
        }
        if(StrUtil.isBlank(newPassword)){
            return BizResponseUtil.fail("新密码不正确");
        }
        try{
            if(!StrUtil.isBlank(userId)){
                svr.modifyPassword(userId, newPassword);
                //更新登录时间
                svr.updateLoginTime(userId);
                addOperationLog("密码修改",String.format("修改%s密码", userId));
                return BizResponseUtil.success(MSG_ExeOK);
            }
            else{
                return BizResponseUtil.fail("你还未登录");
            }
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
    }

	/**
	 * 图片上传
	 */
	@PostMapping("/picUpload")
	public BizResponse picUpload(MultipartFile file,String uid) {
		String filePath = "";
		try {
			logger.debug("get file:{}:{}", file.getOriginalFilename(), file.getName());
			String localFileName = UploadFileUtil.uploadFile(file, "head",uid);
			logger.debug("save file:{}", localFileName);
			return BizResponseUtil.single(localFileName);
		} catch (PcivException ex){
			logger.warn(MSG_ExeERROR, ex);
			return BizResponseUtil.error(ex);
		} catch(Exception e){
			logger.warn(MSG_ExeERROR, e);
			return BizResponseUtil.fail(MSG_ExeERROR+e.getMessage());
		}
	}
}
